<template>
  <div v-loading="loading" :element-loading-text="elementLoadingText">
    <div class="uploadBody">
      <!-- 上传 -->
      <div v-if="isCheck" v-loading="upload.loading">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".docx, .doc, .pdf"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :before-upload="handleBeforeUpload"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或') }}
            <em>{{ $t('点击上传') }}</em>
          </div>
          <div slot="tip" class="el-upload__tip" style="color:red">
            {{ $t('提示：仅支持导入 doc、docx、pdf格式文件！') }}
          </div>
        </el-upload>
      </div>
      <div v-else class="state_main">
        <!-- 审核状态: 0未审核；1审核中；2审核完成；3回调完成；4配额不足； -->
        <div v-if="fileExamineRecord == null || fileExamineRecord.status == null || fileExamineRecord.status === '0'" class="state" style="color:#909399;">
          <i class="iconfont icon-tishi-mianxing" />
          <p>{{ '未审核' }}</p>
        </div>
        <div v-else-if="fileExamineRecord.status === '1'" class="state" style="color:#E6A23C;">
          <i class="iconfont icon-shijian-mianxing" />
          <p>{{ '审核中' }}</p>
        </div>
        <div v-else-if="fileExamineRecord.status === '2'" class="state" style="color:#67C23A;">
          <i class="iconfont icon-zhengque-mianxing" />
          <p>{{ '审核完成' }}</p>
        </div>
        <div v-else-if="fileExamineRecord.status === '4'" class="state" style="color:#fa8c16;">
          <i class="iconfont icon-zhengque-mianxing" />
          <p>{{ '配额不足' }}</p>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button type="info" @click="fileExamineRecordHistory">{{ $t('检查记录') }}</el-button>
      <el-button v-if="fileExamineRecord.status === '2'" type="success" @click="startNewCheck">{{ $t('开启新的检查') }}</el-button>
      <el-button v-if="fileExamineRecord.status === '2'" type="primary" @click="resultDownload">{{ $t('下载结果') }}</el-button>
    </div>
    <el-dialog
      title="检查记录"
      :visible.sync="historyOpen"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :modal-append-to-body="false"
      :modal="false"
      :destroy-on-close="true"
      width="80%"
      custom-class="dialogView"
      append-to-body
    >
      <fileExamineRecordList ref="fileExamineRecordList" />
    </el-dialog>
  </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getToken } from '@/utils/auth'
import { getDocReviewResult } from '@/api/file/fileBase'
import fileExamineRecordList from '@/views/file/documentCheck/fileExamineRecordList'
export default {
  components: {
    fileExamineRecordList
  },
  data() {
    return {
      // 指定文件后缀
      specifyFileSuffix: ['doc', 'docx', 'pdf'],
      loading: false,
      historyOpen: false,
      fileExamineRecord: {
        id: undefined,
        fileId: undefined,
        openId: undefined,
        status: '',
        statusName: undefined,
        commentFileUrl: undefined
      },
      elementLoadingText: 'loading...',
      upload: {
        // 是否显示弹出层（项目导入）
        open: false,
        // 弹出层标题（项目导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/examineRecord/fileExamineRecord/documentCheck',
        // 遮罩层
        loading: false
      },
      isCheck: true
    }
  },
  computed: {
  },
  created() {
  },
  mounted() {
    setInterval(() => {
      if ((this.fileExamineRecord.openId !== null && this.fileExamineRecord.openId !== undefined && this.fileExamineRecord.openId !== '') && this.fileExamineRecord.status !== '2') {
        this.queryResults()
      }
    }, 1000)
  },
  methods: {
    // 历史检查记录
    fileExamineRecordHistory() {
      this.historyOpen = true
      this.$nextTick(() => {
        this.$refs.fileExamineRecordList.getList()
      })
    },
    // 查询文档检查结果
    queryResults() {
      // 根据文件id修改fileTag
      if (this.fileExamineRecord.openId === null || this.fileExamineRecord.openId === undefined || this.fileExamineRecord.openId === '') {
        console.log(this.fileExamineRecord)
        return
      }
      getDocReviewResult(this.fileExamineRecord.openId).then(response => {
        if (response.code === 200) {
          this.fileExamineRecord = response.data
          if (this.fileExamineRecord.status === '2') {
            this.startCheck = false
          }
          console.log('获取文件审核返回结果数据', response)
        } else {
          this.msgError(response.msg)
        }
      })
    },
    downloadFile(url, fileName) {
      var x = new XMLHttpRequest()
      x.open('GET', url, true)
      x.responseType = 'blob'
      x.onload = function() {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a')
        a.href = url
        a.download = fileName
        a.click()
      }
      x.send()
    },
    // 文件下载
    resultDownload() {
      const url = this.fileExamineRecord.commentFileUrl
      var docAll = url.substring(url.lastIndexOf('/') + 1)
      var fileName = docAll.substring(0, docAll.lastIndexOf('.') + 1)
      this.downloadFile(url, fileName)
    },
    // 开启新的检查
    startNewCheck() {
      this.isCheck = true
      this.fileExamineRecord = {
        id: undefined,
        fileId: undefined,
        openId: undefined,
        status: '',
        statusName: undefined,
        commentFileUrl: undefined
      }
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
      // this.upload.loading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.isCheck = true
      console.log(response)
      this.upload.open = false
      this.upload.isUploading = false
      // this.upload.loading = false
      this.$refs.upload.clearFiles()
      if (response.code === 200) {
        // this.msgSuccess(this.$t('开始检查'))
        this.fileExamineRecord = response.data
        this.isCheck = false
      } else if (response.code === 500) {
        this.msgError(this.$t('数据异常'))
      } else {
        this.$notify({
          title: this.$t(response.msg),
          message: '',
          type: 'success'
        })
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    handleBeforeUpload(file, fileList) {
      console.log(file, fileList)
      // 档审核目前支持doc、docx、pdf格式文件审核，最大支持50w字，1GB大小的文件
      var flag = false
      const availableSuffixes = '.doc.docx.pdf'
      const suffix = file.name.substr(file.name.lastIndexOf('.') + 1, file.name.length)
      if (!availableSuffixes.includes(suffix)) {
        flag = true
      }
      if (flag) {
        this.msgError(this.$t('仅支持导入 doc、docx、pdf格式文件！'))
        this.$refs.upload.clearFiles()
        return false
      }
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('可上传文件数量已达到上限'))
    }
  }
}
</script>

<style lang="scss" scoped>
.state_main{
  margin: 50px auto 40px;
  text-align: center;
  .state{
    i{
      font-size: 80px;
    }
    p{
      font-weight: bold;
      font-size: 16px;
      margin: 0;
      margin-top: 10px;
    }
  }
}
</style>
